<?php

require_once "Db.php";

class Cate extends Db {

    function getListCate($parent_id = -1 ,$type = -1) {
        $sql = "SELECT * FROM category WHERE (parent_id = $parent_id or $parent_id = -1) ";
        if($type > 0) $sql.= " AND type = $type ";
        $sql.= " ORDER BY cate_id";        
        $rs = mysql_query($sql) or die(mysql_error());
        return $rs;
    }    
    function insertCate() {
        $parent_id = (int) $_POST['parent_id'];

        $cate_name = $this->processData($_POST['cate_name']);

        $update_time = time();         
        $type= (int) $_POST['type'];
        
        $cate_alias = $this->changeTitle($cate_name);

        $sql = "INSERT INTO category VALUES(NULL,'$cate_name','$cate_alias',$parent_id,$type,'$cate_name','$cate_name','$cate_name',$update_time)";								
        mysql_query($sql) or die(mysql_error() . $sql);
    }
    function updateCate($cate_id) {
        $parent_id = (int) $_POST['parent_id'];

        $cate_name = $this->processData($_POST['cate_name']);
         $type= (int) $_POST['type'];
        $update_time = time();         
        
        $cate_alias = $this->changeTitle($cate_name);

         $sql = "UPDATE category
                SET cate_name = '$cate_name',cate_alias = '$cate_alias',
                parent_id = $parent_id,update_time = $update_time,	
                type='$type',
                seo_title = '$cate_name',seo_description = '$cate_name',seo_keyword = '$cate_name'					
                WHERE cate_id = $cate_id ";
        mysql_query($sql) or die(mysql_error() . $sql);
    }
    function getDetailCate($cate_id){
        $sql = "SELECT * FROM category WHERE cate_id = $cate_id";
        $rs = mysql_query($sql) or die(mysql_error());
        return $rs;
    }
    function getProductCodeByCateId($cate_id){
        $sql = "SELECT product_code FROM product WHERE category_id = $cate_id ORDER BY product_id DESC LIMIT 0,1";
        $rs_1 = mysql_query($sql);
        if(mysql_num_rows($rs_1)==1){
            $row = mysql_fetch_assoc($rs_1);
            $arr = explode("_",$row['product_code']);
            $code = (int) end($arr);
            if($code>0) $str = str_pad (($code+1), 3, "0", 'STR_PAD_LEFT');
        }else{
            $str =  "001";
        }
        return $str;
    }
    function getCode($cate_id){
        $rs = $this->getDetailCate($cate_id);
        $row = mysql_fetch_assoc($rs);
        $cate_name = $row['cate_name'];
        $cate_name_return = $this->changeCode($cate_name);
        $code = $this->getProductCodeByCateId($cate_id);
        $a =  $cate_name_return."_".$code;
        return $a;
    }
}

?>